//登录与注册的模块
import { reqSendCode, reqRegister, reqLogin, reqUserInfo, reqLogout } from '@/api/index'
import { setToken, removeToken } from '@/utils'
const state = {
    code: '',//验证码
    //默认获取本地的token
    token: localStorage.getItem('TOKEN'),
    userInfo: {} //用户信息
}
const actions = {
    //获取验证码
    async getSendCode({ commit }, phone) {
        let result = await reqSendCode(phone)
        //获取验证码的接口是吧验证码返回
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else return Promise.reject(new Error('faile'))
    },
    //确认注册
    async userRegister({ commit }, userInfo) {
        let result = await reqRegister(userInfo)
        if (result.code == 200) {
            return 'ok'
        } else return Promise.reject(new Error(result.message))
    },
    //登录
    async login({ commit }, data) {
        let result = await reqLogin(data)
        //登录成功会返回用户信息，其中token作为用户唯一标识符
        if (result.code == 200) {
            commit('USERTOKEN', result.data.token)
            //持久化储存token
            setToken(result.data.token)
            return 'ok'
        } else return Promise.reject(new Error(result.message))
    },
    //获取用户信息
    async getUserInfo({ commit }) {
        let res = await reqUserInfo()
        if (res.code == 200) {
            commit('USERINFO', res.data)
            return 'ok'
        } else return Promise.reject(new Error(result.message))
    },
    //退出登录
    async logout({ commit }) {
        //发请求清除服务器的token
        let res = await reqLogout()
        if (res.code == 200) {
            //提交mutations清除用户信息
            commit('CLEAR')
            return 'ok'
        } else return Promise.reject(new Error(result.message))
    }
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERTOKEN(state, data) {
        state.token = data
    },
    USERINFO(state, data) {
        state.userInfo = data
    },
    CLEAR(state) {
        state.userInfo = {}
        state.token = ''
        removeToken()
    }
}
const getters = {}

export default {
    actions, state, mutations, getters
}